package com.zhang.authoritycenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.authoritycenter.common.model.dao.sys.SysDirectionCategoryDO;
import com.zhang.authoritycenter.common.model.dao.sys.SysDirectionDO;
import com.zhang.authoritycenter.common.model.dto.sys.DirectionReqExtDTO;
import com.zhang.authoritycenter.common.model.dto.sys.SystemDirectionReqDTO;
import com.zhang.authoritycenter.common.model.vo.sys.SystemDirectionDetailResDTO;
import com.zhang.authoritycenter.dao.sys.SysDirectionCategoryMapper;
import com.zhang.authoritycenter.dao.sys.SysDirectionMapper;
import com.zhang.authoritycenter.service.ISysDirectionService;
import com.zhang.infrastructure.api.authority.DirectionRemoteVO;
import com.zhang.infrastructure.api.authority.DirectionReqRemoteDTO;
import com.zhang.infrastructure.model.KingHoodResponseVO;
import com.zhang.infrastructure.model.constant.CommonConstants;
import com.zhang.infrastructure.util.UserUtil;
import com.zhang.infrastructure.util.base.IdGenUtil;
import com.zhang.sharding.model.KingHoodPageUtil;
import com.zhang.sharding.model.KingPageResult;
import com.zhang.sharding.model.PageResponseVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统数据字典表 服务实现类
 * </p>
 *
 * @author KingHood
 * @since 2023-12-20
 */
@Service
public class SysDirectionServiceImpl extends ServiceImpl<SysDirectionMapper, SysDirectionDO> implements ISysDirectionService {
    @Resource
    private SysDirectionMapper SysDirectionDOMapper;
    @Resource
    SysDirectionCategoryMapper SysDirectionCategoryDOMapper;

    @Override
    public PageResponseVO<?> queryDirectionPageList(DirectionReqExtDTO query) {
        Page<SystemDirectionDetailResDTO> list = SysDirectionDOMapper.queryPage(KingHoodPageUtil.getPage(query, query), query);
        list.getRecords().stream().forEach(i -> i.genBelongType());
        return KingPageResult.getResult(list);

    }

    /**
     * TODO:指定编码
     *
     * @param query
     * @return
     * @version 2019年7月5日上午9:57:41
     * @author Mike
     */
    @Override
    public KingHoodResponseVO<?> queryDirectionBycode(DirectionReqExtDTO query) {
        if (StringUtils.isEmpty(query.getDataCode())) {
            return KingHoodResponseVO.fail(-1, "参数不能为空");

        }
        QueryWrapper<SysDirectionDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("data_code", query.getDataCode()).eq("is_delete", 0);
        List<SysDirectionDO> list = SysDirectionDOMapper.selectList(queryWrapper);
        return KingHoodResponseVO.success(list);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public KingHoodResponseVO<?> addorUpdateDirection(@Valid SystemDirectionReqDTO dirReq) {
        QueryWrapper<SysDirectionCategoryDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("data_code", dirReq.getDataCode()).eq("is_delete", 0);
        List<SysDirectionCategoryDO> list = SysDirectionCategoryDOMapper.selectList(queryWrapper);
        if (list.isEmpty()){
            return KingHoodResponseVO.fail(-1, "查找不到相应的类型，请输入正确到类型");
        }
        SysDirectionDO sd = new SysDirectionDO();
        QueryWrapper<SysDirectionDO> checkWrapper = new QueryWrapper<SysDirectionDO>();
        checkWrapper.eq("data_code", dirReq.getDataCode());
        checkWrapper.eq("data_key", dirReq.getDataKey());
        checkWrapper.eq("is_delete", 0);
        if (Objects.isNull(dirReq.getId())) {
            dirReq.setCreateTime(new Date());
            dirReq.setVersion(0);
            BeanUtils.copyProperties(dirReq, sd);
            sd.setId(IdGenUtil.get().nextId());
            sd.setCreateTime(LocalDateTime.now());
            sd.setCreateUserId(UserUtil.getUserId());
            Long listSys = SysDirectionDOMapper.selectCount(checkWrapper);
            if (listSys.intValue() > 0){
                return KingHoodResponseVO.fail(-1, "key或数据名称重复");
            }

            SysDirectionDOMapper.insert(sd);
        } else {
            checkWrapper.ne("id", dirReq.getId());
            Long listSys = SysDirectionDOMapper.selectCount(checkWrapper);
            if (listSys != null && listSys > 0){
                return KingHoodResponseVO.fail(-1, "key不存在");
            }
            dirReq.setUpdateTime(new Date());
            dirReq.setVersion(1);
            BeanUtils.copyProperties(dirReq, sd);
            if (Strings.isBlank(dirReq.getPictures())) {
                sd.setPictures("");
            }
            SysDirectionDOMapper.updateById(sd);
        }
        return KingHoodResponseVO.success();
    }

    /**
     * 排序
     *
     * @param dirReq
     * @return
     * @date 2019年11月4日下午3:55:12
     * @author Mike
     */
    @Override
    public KingHoodResponseVO<?> updateSort(SystemDirectionReqDTO dirReq) {
        this.lambdaUpdate()
                .set(SysDirectionDO::getSortNumber, dirReq.getSortNumber())
                .set(SysDirectionDO::getUpdateTime, LocalDateTime.now())
                .set(SysDirectionDO::getUpdateUserId, UserUtil.getUserId())
                .eq(SysDirectionDO::getId, dirReq.getId())
                .update();
        return KingHoodResponseVO.success();
    }

    /**
     * 删除
     *
     * @param id
     * @return
     * @date 2019年11月4日下午3:55:23
     * @author Mike
     */
    @Override
    public KingHoodResponseVO<?> delDirectionById(Long id) {
        this.lambdaUpdate()
                .set(SysDirectionDO::getIsDelete, CommonConstants.IS_DELETE_Y)
                .set(SysDirectionDO::getUpdateUserId, UserUtil.getUserId())
                .set(SysDirectionDO::getUpdateTime, LocalDateTime.now())
                .eq(SysDirectionDO::getId, id)
                .eq(SysDirectionDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .update();
        return KingHoodResponseVO.success();
    }

    /**
     * 获取
     *
     * @param id
     * @return
     * @version 2019年7月5日上午10:26:03
     * @author Mike
     */
    @Override
    public KingHoodResponseVO<?> queryDirectionById(Long id) {
        SystemDirectionDetailResDTO result = new SystemDirectionDetailResDTO();
        SysDirectionDO directionDO = SysDirectionDOMapper.selectById(id);
        if (Objects.nonNull(directionDO)) {
            BeanUtils.copyProperties(directionDO, result);
            result.genBelongType();
        }
        return KingHoodResponseVO.success(result);
    }

    /**
     * @description: 机构可选字典下拉选项列表
     * @date: 2023/4/6 11:05
     * @Author: Tom
     * @param: [directionReqExtDTO, many]
     * @return: Map<String, List < SysDirectionDO>>
     */
    @Override
    public Object selectOptionList(DirectionReqExtDTO directionReqExtDTO, boolean many) {
        Map<String, List<SysDirectionDO>> mapForBank = null;

        if (CollectionUtils.isNotEmpty(directionReqExtDTO.getDataCodeList())) {
            List<SysDirectionDO> SysDirectionDOList = SysDirectionDOMapper.selectOptionList(directionReqExtDTO);
            if (CollectionUtils.isNotEmpty(SysDirectionDOList)) {
                Map<String, List<SysDirectionDO>> map = SysDirectionDOList.stream().collect(Collectors.groupingBy(item -> item.getDataCode()));
                if (mapForBank == null || mapForBank.isEmpty()) {
                    if (!many && map != null && !map.isEmpty()) {
                        Map<String, Object> mapSingle = new HashMap<>();
                        Iterator<Map.Entry<String, List<SysDirectionDO>>> iterator = map.entrySet().iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, List<SysDirectionDO>> next = iterator.next();
                            if (next.getValue().size() == 1) {
                                mapSingle.put(next.getKey(), next.getValue().get(0));
                            } else {
                                mapSingle.put(next.getKey(), next.getValue());
                            }
                        }

                        return mapSingle;
                    }
                    return map;
                }
                mapForBank.putAll(map);
            }
        }

        if (!many && mapForBank != null && !mapForBank.isEmpty()) {
            Map<String, Object> mapSingle = new HashMap<>();
            Iterator<Map.Entry<String, List<SysDirectionDO>>> iterator = mapForBank.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, List<SysDirectionDO>> next = iterator.next();
                if (next.getValue().size() == 1) {
                    mapSingle.put(next.getKey(), next.getValue().get(0));
                } else {
                    mapSingle.put(next.getKey(), next.getValue());
                }
            }

            return mapSingle;
        }

        return mapForBank;
    }

    @Override
    public List<DirectionRemoteVO> getDirectionByCodeList(DirectionReqRemoteDTO directionReqExtDTO) {
        List<DirectionRemoteVO> result = this.baseMapper.getDirectionByCodeList(directionReqExtDTO);
        return result;
    }
}
